package net;

import java.nio.ByteOrder;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;

public class Client {
	public Channel channel;
	public int version;	
	public int handlingMessageRID;
	public String uuid;
	
	private int _headIndex;
	private ChannelBuffer _sending;
	
	public ChannelBuffer prepareMsg(String name, int size) {
		_sending = ChannelBuffers.dynamicBuffer(ByteOrder.LITTLE_ENDIAN, size);
		_headIndex = _sending.writerIndex();
		_sending.writeInt(0);
		Protocol.writeString(_sending, name);
		_sending.writeInt(handlingMessageRID);
		return _sending;
	}
	
	public ChannelBuffer prepareMsg(String name) {
		return prepareMsg(name, 1024);		
	}
	
	public ChannelBuffer prepareQueryResult() {
		return prepareMsg("QueryResult");
	}
	
	public void sendMessageAndClose() {
		sendMsg().addListener(ChannelFutureListener.CLOSE);
		channel = null;
		_sending = null;
	}
	
    public ChannelFuture sendMsg() {
    	int len = _sending.writerIndex() - _headIndex - Protocol.HEAD_LENGTH;
    	_sending.setInt(_headIndex, len);
    	return channel.write(_sending);
    }
}
